package DAO;


import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import Model.book;

/**
 * 书本数据库操作类
 * @author MacBook
 *
 */
public class bookDAO {
	//添加书本
	public static void save(Session session,book b){
		session.save(b);
	}
	//删除书本
	public static void delete(Session session,book b){
		session.delete(b);
	}
	//查找书本
	public static book findByName(Session session,String name){
		String hql = "from book where bookname = ?";
		Query<?> query = session.createQuery(hql);
		query.setParameter(0, name);
		List list = query.list();
		book book = null;
		if(list.size() != 0)
			book =(book) list.get(0);
		return book;
	}
	//修改书本信息 
	public static void  update(Session session,int bookid,String updateName){
		book b = (book) session.load(book.class, bookid);
		b.setBookname(updateName);
		session.update(b);
	}
	//分页查询
	public static List<book> pageSelect(Session session,int start,int size){
		String hql = "from book";
		Query<?> query = session.createQuery(hql);
		query.setFirstResult(start);//开始索引
		query.setMaxResults(size);//取几条
		List list = query.list();
		return list;
	}
	//获取书本的条数 
	public static int getBookCount(Session session){
		String hql="SELECT COUNT(*) FROM book";
		Query<?> query = session.createQuery(hql);
		return ((Number)query.uniqueResult()).intValue();  
	}
	//查询书本的数量
	public static int getBookNumber(Session session,int bookid){
		String hql="SELECT numbers FROM book where bookid = ?";
		Query<?> query = session.createQuery(hql);
		query.setParameter(0, bookid);
		if(query.uniqueResult() != null)
			return ((Number)query.uniqueResult()).intValue();  
		else
			return -1;
	}
	//借出
	public static void bookout(Session session,int bookid){
		String hql = "update book set numbers = numbers - 1 where bookid = ?";
		Query<?> query = session.createQuery(hql);
		query.setParameter(0, bookid);
		query.executeUpdate();
	}
	//还书
	public static void bookin(Session session,int bookid){
		String hql = "update book set numbers = numbers + 1 where bookid = ?";
		Query<?> query = session.createQuery(hql);
		query.setParameter(0, bookid);
		query.executeUpdate();
	}
}
